import threading
import uuid
from abc import abstractmethod
from datetime import datetime

from apps.logger_config import logger


class Job(threading.Thread):
    __job_name__ = ''

    def __init__(self, *args, **kwargs):
        super(Job, self).__init__(*args, **kwargs)
        self.__flag = threading.Event()  # 用于暂停线程的标识
        self.__flag.set()  # 设置为True
        self.__running = threading.Event()  # 用于停止线程的标识
        self.__running.set()  # 将running设置为True
        self.running = threading.Event()
        self.running.set()  # 将running设置为True

    def run(self):
        while self.__running.isSet():
            self.__flag.wait()  # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回
            uid = uuid.uuid4()
            logger.info('*' * 36)
            logger.info('程序：%s, 开始时间：%s， UUID: %s', self.__job_name__, datetime.now().isoformat(), uid)
            try:
                self.executor(str(uid))
            except Exception as e:
                logger.error(
                    '程序：%s, 结束时间：%s， UUID: %s， Error: %s',
                    self.__job_name__,
                    datetime.now().isoformat(),
                    uid,
                    e
                )
                self.stop()
                break
            # logger.info('程序：%s, 结束时间：%s， UUID: %s', self.__job_name__, datetime.now().isoformat(), uid)
            logger.info('*' * 36)

    @abstractmethod
    def executor(self, uid: str):
        pass

    def pause(self):
        self.__flag.clear()  # 设置为False, 让线程阻塞

    def resume(self):
        self.__flag.set()  # 设置为True, 让线程停止阻塞

    def stop(self):
        self.__flag.set()  # 将线程从暂停状态恢复, 如何已经暂停的话
        self.__running.clear()  # 设置为False
        self.running.clear()
